<?php

namespace app\admin\controller\other;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 产品工序方案
 *
 * @icon fa fa-circle-o
 */
class Process extends Backend
{

    /**
     * Process模型对象
     * @var \app\admin\model\other\Process
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\other\Process;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['colour', 'attribute'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
//            p($list);
            if ($list->total()) {
                $list = addtion($list, 'process_attribute_ids');
                $list = addtion($list, 'colour_ids');
            }
            foreach ($list as $row) {
                $row->visible(['id', 'trademark_printing', 'colour_ids', 'process_attribute_ids', 'createtime', 'updatetime', 'status', 'process_attribute_names', 'colour_names']);
                $row->visible(['colour']);
                $row->getRelation('colour')->visible(['name']);
                $row->visible(['attribute']);
                $row->getRelation('attribute')->visible(['name']);
            }


            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);

                    if ($result) {
                        //是否有未关联工序的订单
                        $where['trademark_printing'] = $params['trademark_printing'];
                        $where['colour_id'] = array('in', explode(',', $params['colour_ids']));
                        $where['process_detail'] = null;
                        $orderDetailArr = Db::name('order_detail')->where($where)->column('id');

                        if ($orderDetailArr && is_array($orderDetailArr)) {
                            $processList = explode(',', $params['process_attribute_ids']);
                            $process_detail = [];
                            foreach ($processList as $k2 => $v2) {
                                $new_data['process_attribute'] = $v2;
                                $new_data['quantity'] = 0; //工序收取量
                                $new_data['schedule'] = 0; //工序进度=工序累计收取量/订单总数*100
                                $new_data['weights'] = 0; //工序权重 = 工序收取量/色号收取总数*工序进度/100
                                $process_detail[] = $new_data;
                            }
                            $upOrderDetail['process_detail'] = json_encode($process_detail, JSON_UNESCAPED_UNICODE);

                            $re = Db::name('order_detail')->where('id', 'in', $orderDetailArr)->update($upOrderDetail);
                            foreach ($orderDetailArr as $k3 => $v3) {
                                //更细订单进度
                                up_order_schedule($v3);
                            }

                        }

                    }
//                    Db::rollback();
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {

        //获取旧数据
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $ColourArr = explode(',', $row['colour_ids']); //旧的色号数组
                    $newColourArr = explode(',', $params['colour_ids']); //新的的色号数组
                    $oldProcessArr = explode(',', $row['process_attribute_ids']); //旧的工序数组
                    $newProcessArr = explode(',', $params['process_attribute_ids']); //新的的工序数组


                    //查找出减少的色号
                    $lowerColourArr = array_diff($ColourArr, $newColourArr);
                    //判断是否存在收货记录
                    $lowerColourWhere['od.trademark_printing'] = $params['trademark_printing'];
                    $lowerColourWhere['r.colour_id'] = ['in', $lowerColourArr];
                    $lowerColourRe = Db::name('receiving')->alias('r')
                        ->join('order_detail od', 'od.id = r.order_detail_id')
                        ->where($lowerColourWhere)->count();
                    if ($lowerColourRe > 0) {
                        $colourNameStr = '[';
                        foreach (collection(Db::name('colour')->where('id', 'in', $lowerColourArr)->field('name')->select())->toArray() as $key => $value) {
                            $colourNameStr .= $value['name'] . ',';
                        }
                        $colourNameStr = substr($colourNameStr, 0, strlen($colourNameStr) - 1) . ']';

                        Db::rollback();
                        $this->error('当前商标印字下已经存在一下色号' . $colourNameStr . '的收货记录，不能删除！');
                    }


                    //查找出新增的色号
                    $addColourArr = array_diff($newColourArr, $ColourArr);
                    //判断订单中是否有新增色号+商标印字的数据
                    $addColourWhere['trademark_printing'] = $params['trademark_printing'];
                    $addColourWhere['colour_id'] = ['in', $addColourArr];
                    $addColourWhere['process_detail'] = null;
                    $addColourRe = Db::name('order_detail')
                        ->where($addColourWhere)->column('id');

                    if ($addColourRe && is_array($addColourRe)) {
                        $processList = $newProcessArr;
                        $process_detail = [];
                        foreach ($processList as $k2 => $v2) {
                            $new_data['process_attribute'] = $v2;
                            $new_data['quantity'] = 0; //工序收取量
                            $new_data['schedule'] = 0; //工序进度=工序累计收取量/订单总数*100
                            $new_data['weights'] = 0; //工序权重 = 工序收取量/色号收取总数*工序进度/100
                            $process_detail[] = $new_data;
                        }
                        $upOrderDetail['process_detail'] = json_encode($process_detail, JSON_UNESCAPED_UNICODE);

                        $re = Db::name('order_detail')->where('id', 'in', $addColourRe)->update($upOrderDetail);
                        foreach ($addColourRe as $k3 => $v3) {
                            //更细订单进度
                            up_order_schedule($v3);
                        }

                    }


                    //查找出减少的工序
                    $lowerProcessArr = array_diff($oldProcessArr, $newProcessArr);
                    //查找出新增的工序
                    $addProcessArr = array_diff($newProcessArr, $oldProcessArr);

                    $result = $row->allowField(true)->save($params);
                    $changeOrderArr = [];

                    if ($result) {
//                        p($lowerColourArr && is_array($lowerColourArr));
                        //删除色号,清空商品明细中的工序明细
                        if ($lowerColourArr && is_array($lowerColourArr)) {
                            $delWhere['trademark_printing'] = $params['trademark_printing'];
                            $delWhere['colour_id'] = ['in', $lowerColourArr];
                            $rr = Db::name('order_detail')->where($delWhere)->update(['process_detail' => null]);

                        }

                        if ($lowerProcessArr) {
                            //判断减少的工序是否存在收货数据
                            foreach ($ColourArr as $k => $v) {
                                foreach ($lowerProcessArr as $k2 => $v2) {
                                    if (is_has_received($params['trademark_printing'], $v, $v2)) {
                                        $colour = Db::name('colour')->where('id', 'eq', $v)->value('name');
                                        $process = Db::name('process_attribute')->where('id', 'eq', $v2)->value('name');
                                        Db::rollback();
                                        $this->error('已经存在[' . $params['trademark_printing'] . '+' . $colour . '+' . $process . ']的收货记录，不能删除！');
                                    } else {
                                        //查找使用当前 商标印字+色号组合的订单数据
                                        $orderDetailWhere['trademark_printing'] = $params['trademark_printing'];
                                        $orderDetailWhere['colour_id'] = $v;
                                        $orderDetailArr = Db::name('order_detail')->where($orderDetailWhere)->select();
                                        if ($orderDetailArr) {
                                            foreach ($orderDetailArr as $k2 => $v2) {
                                                $processList = $lowerProcessArr;
                                                $process_detail = [];
                                                if ($v2['process_detail']) $process_detail = \GuzzleHttp\json_decode($v2['process_detail'], true);

                                                foreach ($processList as $k3 => $v3) {
                                                    foreach ($process_detail as $k4 => $v4) {
                                                        if ($v4['process_attribute'] == $v3) {
                                                            unset($process_detail[$k4]);
                                                            if (!in_array($v2['order_id'], $changeOrderArr)) {
                                                                $changeOrderArr[] = $v2['order_id'];
                                                            }
                                                        }
                                                    }

                                                }
                                                $upOrderDetail['process_detail'] = json_encode($process_detail, JSON_UNESCAPED_UNICODE);

                                                $re = Db::name('order_detail')->where('id', 'eq', $v2['id'])->update($upOrderDetail);
                                                if ($re) {

                                                    if (!in_array($v2['order_id'], $changeOrderArr)) {
                                                        $changeOrderArr[] = $v2['order_id'];
                                                    }
                                                } else {
                                                    Db::rollback();
                                                    $this->error('修改失败，稍后再试！');
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if ($addProcessArr) {
                            foreach ($ColourArr as $k => $v) {
                                //查找使用当前 商标印字+色号组合的订单数据
                                $orderDetailWhere['trademark_printing'] = $params['trademark_printing'];
                                $orderDetailWhere['colour_id'] = $v;
                                $orderDetailArr = Db::name('order_detail')->where($orderDetailWhere)->select();

                                if ($orderDetailArr) {
                                    foreach ($orderDetailArr as $k2 => $v2) {
                                        $processList = $addProcessArr;
                                        $process_detail = [];
                                        if ($v2['process_detail']) $process_detail = \GuzzleHttp\json_decode($v2['process_detail'], true);

                                        foreach ($processList as $k3 => $v3) {
                                            $new_data['process_attribute'] = $v3;
                                            $new_data['quantity'] = 0; //工序收取量
                                            $new_data['schedule'] = 0; //工序进度=工序累计收取量/订单总数*100
                                            $new_data['weights'] = 0; //工序权重 = 工序收取量/色号收取总数*工序进度/100
                                            array_push($process_detail, $new_data);
                                        }

                                        $upOrderDetail['process_detail'] = json_encode($process_detail, JSON_UNESCAPED_UNICODE);

                                        $re = Db::name('order_detail')->where('id', 'eq', $v2['id'])->update($upOrderDetail);

                                        if ($re) {
                                            if (!in_array($v2['order_id'], $changeOrderArr)) {
                                                $changeOrderArr[] = $v2['order_id'];
                                            }
                                        } else {
                                            Db::rollback();
                                            $this->error('修改失败，稍后再试！');
                                        }
//                                        p($changeOrderArr);
                                    }
                                }
                            }

                        }
                    }

                    if ($changeOrderArr) {
                        foreach ($changeOrderArr as $k3 => $v3) {
                            //更细订单进度
                            up_order_schedule($v3);
                        }
                    }


                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
